import { useKBStoreHook } from "@/stores/modules/KB";
import type { CanvasData } from "@/stores/modules/canvas/helper";
// @ts-ignore
import fonts from "@/assets/icons/iconfont.json";
// import { nodeOptions } from "@/views/associationAnalysis/canvas/components/canvasG6/common/state";

function dropFilter(arr) {
  // ele：当前元素的值，index：当前元素的索引值，arr：原数组
  return arr.filter((ele, index, arr) => {
    // 通过索引筛掉相同的项 id为对象中唯一值
    return arr.findIndex((item) => item.id === ele.id) === index;
  });
}

const icons = fonts.glyphs.map((icon) => {
  return {
    name: icon.name,
    unicode: String.fromCodePoint(icon.unicode_decimal), // `\\u${icon.unicode}`,
  };
});
const getIcon = (type: string) => {
  const matchIcon = icons.find((icon) => {
    return icon.name === type;
  }) || { unicode: "", name: "default" };
  return matchIcon.unicode;
};

const useKBStore = useKBStoreHook();

const makeTags = () => {
  const Tags = useKBStore.tags;
  const set = {};
  Tags.forEach((item) => {
    const props = {};
    item.propertyDTOList.forEach((ele) => {
      props["props_" + ele.code] = ele.name;
    });
    set[item.code] = {
      ...item,
      ...props,
    };
  });
  console.log(set, "set");
  return function (key1: string, key2?: string) {
    if (key2) {
      return set[key1]?.[key2];
    }
    return set[key1];
  };
};

export const getKeyValue = makeTags();
export default function (nodes, data): CanvasData {
  const Nodes = nodes.map((item) => {
    item.tags.forEach((ele) => {
      if (ele.name !== "com") {
        item.tageName = ele.name;
      }
    });
    console.log(item, "getKeyValue");
    // item.backgroundColor = getKeyValue(item.tageName, "backgroundColor"); // node的交互需要
    return {
      ...item,
      size: 48,
      type: getKeyValue(item.tageName, "icon") ? "iconfont" : "my-circle",
      icon: getKeyValue(item.tageName, "icon"),
      text: getKeyValue(item.tageName, "icon")
        ? getIcon(getKeyValue(item.tageName, "icon"))
        : "",
      //节点样式
      style: {
        lineWidth: 0,
        fill: getKeyValue(item.tageName, "backgroundColor"),
      },
      //节点文字样式
      labelCfg: {
        position: "bottom",
        style: {
          fill: "#222222",
          fontSize: 14,
        },
      },
      // 标注配置
      dimensionCfg: {
        name: "",
        style: {
          fill: "#222222",
          fontSize: 12,
        },
      },
      isLock: false,
      //节点交互事件
      // stateStyles: nodeOptions(item),
    };
  });
  let newdata: CanvasData = {
    nodes: [],
    edges: [],
  };
  if (data.nodes) {
    const newArr = data.nodes.concat(Nodes);
    newdata = {
      nodes: dropFilter(newArr),
      edges: data.edges ?? [],
    };
  } else {
    newdata = {
      nodes: Nodes,
      edges: data.edges ?? [],
    };
  }
  return newdata;
}
